package com.aaa.common.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;

import java.io.UnsupportedEncodingException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @FileName: JwtUtils
 * @Description:
 * @Author: zhz
 * @CreateTime: 2025/9/4 17:32
 * @Version: 1.0.0
 */
public class JwtUtils {
    //密钥，只在服务端声明  不能暴露给客户端
    private static final String SECRET = "bsnzgyztmngd";
    /**
     * 生成token
     * @param payload 载荷,需要在token中存放的数据
     * @return
     */
    public static String generateToken(Map<String, String> payload) throws UnsupportedEncodingException {
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE, 1);
        JWTCreator.Builder builder = JWT.create();
        //载荷,生成token中保存的信息
        payload.forEach(builder::withClaim);
        //流式编程
        return builder.withAudience("admin") //签发对象
                .withIssuedAt(new Date()) //发行时间
                //.withExpiresAt(instance.getTime()) //过期时间
                .sign(Algorithm.HMAC256(SECRET)); //加密算法+盐
    }
    /**
     * 校验token,有异常,即为校验失败
     *
     * @param token token数据
     * @return
     */
    public static boolean verify(String token) {
        try {
            JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
    /**
     * 根据token获取载荷信息
     *
     * @param token token数据
     * @return
     */
    public static Map<String, Claim> getPayloadByToken(String token) {
        try {
            return JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token).getClaims();
        }  catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) throws UnsupportedEncodingException {

        Map<String, String> payload = new HashMap<>();
        payload.put("userName","zhangsan");
        payload.put("realName","张三");
        payload.put("age","18");
        String token = generateToken(payload);
        System.out.println(token);
        String tokenTemp="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJhZG1pbiIsInBob25lTnVtIjoiMTg1MzgwNjI5MDciLCJ1c2VyTmFtZSI6ImFkbWluIiwidXNlcklkIjoiMSIsImlhdCI6MTc1NzA1NzMzN30.l7KMG1XxgHmvWfiZNPhpWOa344PCl2YRXYLfX0ojaJM";
        boolean verify = verify(tokenTemp);
        System.out.println(verify);
        Map<String, Claim> payloadByToken = getPayloadByToken(tokenTemp);
        System.out.println(payloadByToken);
        System.out.println(payloadByToken.get("realName"));
    }
}
